package com.ztomorrow.ying_cun_plus.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.ztomorrow.ying_cun_plus.constant.front.ErrorCodeEnum;
import com.ztomorrow.ying_cun_plus.dto.resp.ImgVerifyCodeRespDto;
import com.ztomorrow.ying_cun_plus.dto.resp.RestResp;
import com.ztomorrow.ying_cun_plus.exception.BusinessException;
import com.ztomorrow.ying_cun_plus.service.ResourceService;
import com.ztomorrow.ying_cun_plus.utils.RedisVerifyCode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static com.ztomorrow.ying_cun_plus.constant.author.SystemConstant.IMAGE_UPLOAD_DIRECTORY;

@Slf4j
@Service
@RequiredArgsConstructor
public class ResourceServiceImpl implements ResourceService {

    private final RedisVerifyCode redisVerifyCode;

    @Value("${yc-plus.file.upload.path}")
    private String uploadDir;

    @Override
    public RestResp<ImgVerifyCodeRespDto> getImgVerifyCode() throws IOException {
        String id = IdUtil.simpleUUID();
        return RestResp.ok(new ImgVerifyCodeRespDto(id, redisVerifyCode.generateVerifyCode(id)));
    }

    @Override
    public RestResp<String> uploadImage(MultipartFile file) throws IOException {

        LocalDateTime now = LocalDateTime.now();
        String savePath = File.separator + IMAGE_UPLOAD_DIRECTORY + File.separator
                + now.format(DateTimeFormatter.ofPattern("yyyy")) + File.separator
                        + now.format(DateTimeFormatter.ofPattern("MM")) + File.separator
                        + now.format(DateTimeFormatter.ofPattern("dd"));
        String oriName = file.getOriginalFilename();
        assert oriName != null;
        String saveFileName = IdWorker.get32UUID() + oriName.substring(oriName.lastIndexOf("."));
        File saveFile = new File(uploadDir + savePath, saveFileName);
        if (!saveFile.getParentFile().exists()) {
            boolean isSuccess = saveFile.getParentFile().mkdirs();
            if (!isSuccess) {
                log.error("Failed to create directories: {}", saveFile.getParentFile().getAbsolutePath());
                throw new BusinessException(ErrorCodeEnum.USER_UPLOAD_FILE_DIR_ERROR);
            }
        }
        Files.write(Paths.get(saveFile.getPath()), file.getBytes());

        return RestResp.ok(savePath + File.separator + saveFileName);
    }
}
